Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(contentful-apps): Allow two project subpages to have same slug #16412

Merged
merged 4 commits into from
Oct 16, 2024

Conversation

RunarVestmann
Copy link
Member

@RunarVestmann RunarVestmann commented Oct 15, 2024

Allow two project subpages to have same slug

What

  • Project subpage slug field is not a contentful app in the cms, meaning that we are overriding the unique slug validation logic so we can have to subpages with the same slug

Why

Example (both of these urls should be allowed):

/v/forsetakosningar-2024/fyrir-kjosendur

/v/althingiskosningar-2024/fyrir-kjosendur

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features
    • Introduced a new component for managing slug fields for project subpages in the Contentful application.
    • Slug generation based on title changes with validation against existing slugs.
    • Enhanced user input handling with real-time feedback and error messages.
    • Automatic resizing of the UI for better user experience.

@RunarVestmann RunarVestmann added the automerge Merge this PR as soon as all checks pass label Oct 15, 2024
@RunarVestmann RunarVestmann requested a review from a team as a code owner October 15, 2024 16:20
Copy link
Contributor

coderabbitai bot commented Oct 15, 2024

Walkthrough

The pull request introduces a new React functional component named ProjectSubpageSlugField in the file project-subpage-slug-field.tsx. This component is designed to manage a slug field for project subpages in a Contentful application, incorporating state management, data fetching, slug generation, validation logic, user input handling, and auto-resizing of the UI.

Changes

File Path Change Summary
apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx Added a new React functional component ProjectSubpageSlugField for managing project subpage slugs.

Possibly related PRs

  • feat(web): Clickable generic list items #15003: The GenericListItemSlugField component also manages slug generation and validation, similar to the ProjectSubpageSlugField, indicating a shared functionality in handling slugs within Contentful applications.

Suggested reviewers

  • mannipje

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (1)

135-136: Slugify user input to ensure consistent slug format

When the user manually edits the slug in the TextInput, the input is set directly without slugification. This could lead to invalid slugs with spaces or special characters. Consider slugifying the user's input to maintain a consistent and valid slug format.

Apply this diff to slugify the user's input:

onChange={(ev) => {
-  setValue(ev.target.value)
+  setValue(slugify(ev.target.value))
}}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f560cd2 and bb8fd2e.

📒 Files selected for processing (1)
  • apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (1)
apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (1)

1-10: Imports and initial setup are appropriate

The imported modules and initial constants are correctly set up, adhering to best practices.

Copy link

codecov bot commented Oct 15, 2024

Codecov Report

Attention: Patch coverage is 0% with 61 lines in your changes missing coverage. Please review.

Project coverage is 36.69%. Comparing base (7a37f44) to head (26f93b5).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...l-apps/pages/fields/project-subpage-slug-field.tsx 0.00% 61 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16412      +/-   ##
==========================================
- Coverage   36.73%   36.69%   -0.04%     
==========================================
  Files        6809     6809              
  Lines      141088   141061      -27     
  Branches    40225    40211      -14     
==========================================
- Hits        51826    51764      -62     
- Misses      89262    89297      +35     
Flag Coverage Δ
contentful-apps 5.44% <0.00%> (-0.14%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...l-apps/pages/fields/project-subpage-slug-field.tsx 0.00% <0.00%> (ø)

... and 12 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 7a37f44...26f93b5. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 15, 2024

Datadog Report

All test runs cbd8601 🔗

11 Total Test Services: 0 Failed, 10 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.12%), 3 increased, 25 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.71s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 12.97s 1 no change Link
api-domains-communications 0 0 0 5 0 30.79s 1 increased (+0.05%) Link
api-domains-license-service 0 0 0 0 0 612.01ms 1 no change Link
application-system-api 0 0 0 120 2 3m 28.46s 1 no change Link
application-template-api-modules 0 0 0 123 0 2m 29.83s 1 no change Link
cms-translations 0 0 0 3 0 26.83s 1 increased (+0.05%) Link
judicial-system-api 0 0 0 57 0 6.24s 1 no change Link
judicial-system-backend 0 0 0 20954 0 19m 36.08s 1 no change Link
services-user-notification 0 0 0 51 0 1m 28.86s 1 increased (+0.04%) Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • contentful-apps - jest 4.7% (-0.12%) - Details

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (1)

24-70: LGTM: Well-structured useEffect hooks with a minor suggestion

The useEffect hooks for data fetching, listening to entry changes, and updating the slug based on title changes are well-implemented. They correctly use the CMA and SDK, and include appropriate checks for published entries and initial render.

A minor suggestion for improvement:

Consider extracting the logic inside the third useEffect (lines 48-66) into a separate function for better readability. For example:

const handleTitleChange = (newTitle: string) => {
  if (hasEntryBeenPublished || initialTitleChange.current) {
    initialTitleChange.current = false;
    return;
  }

  if (newTitle) {
    setValue(slugify(String(newTitle)));
  }
};

useEffect(() => {
  return sdk.entry.fields.title
    .getForLocale(sdk.field.locale)
    .onValueChanged(handleTitleChange);
}, [hasEntryBeenPublished, sdk.entry.fields.title, sdk.field.locale]);

This change would improve the readability and maintainability of the component.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bb8fd2e and 7ae9480.

📒 Files selected for processing (1)
  • apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (4)
apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (4)

1-10: LGTM: Imports and constants are well-organized

The imports are appropriate for the component's functionality, and the debounce time constant is correctly defined at the top level. This follows good practices for React component organization.


11-23: LGTM: Effective state management and initialization

The component's state management using useState hooks is well-structured and appropriate for its needs. The use of useRef to track the initial title change is a good approach to avoid unnecessary updates.


151-151: LGTM: Correct component export

The component is correctly exported as the default export, following common React practices.


80-80: ⚠️ Potential issue

Remove console.log statement

The console.log statement on line 80 should be removed to prevent unwanted console output in production.

Apply this diff to remove the debug statement:

-      console.log(projectPage)

Likely invalid or redundant comment.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (4)
apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (4)

11-23: LGTM: Well-structured component initialization with a suggestion for improvement

The component initialization and state management are well-implemented. The use of hooks for state management and SDK integration is appropriate, and initial states are correctly set up.

A suggestion for improvement:
Consider adding explicit type annotations to the state variables for better type safety and code readability. For example:

const [value, setValue] = useState<string>(sdk.field?.getValue() ?? '')
const [isValid, setIsValid] = useState<boolean>(true)

This change would make the expected types more explicit and could help catch potential type-related issues earlier in development.


24-66: LGTM: Well-implemented effect hooks with a suggestion for optimization

The effect hooks for data fetching, entry changes, and title updates are well-implemented. They correctly handle various scenarios, including ignoring initial renders and respecting the publication status.

A suggestion for optimization:
Consider adding a cleanup function to the data fetching effect to cancel any ongoing requests if the component unmounts or the dependencies change. This can help prevent potential memory leaks or unnecessary API calls. For example:

useEffect(() => {
  let isMounted = true;
  const fetchProjectPage = async () => {
    const response = await cma.entry.getMany({
      // ... existing query ...
    });
    if (isMounted && response.items.length > 0) {
      setProjectPage(response.items[0]);
    }
  };
  fetchProjectPage();
  return () => {
    isMounted = false;
  };
}, [cma.entry, sdk.entry]);

This change ensures that the state is only updated if the component is still mounted, preventing potential issues with setting state on unmounted components.


72-124: LGTM: Well-implemented validation logic and debounced updates with a suggestion for optimization

The validation logic and debounced updates are well-implemented. The use of debounce for both validation and field updates is a good practice to prevent excessive API calls and improve performance.

A suggestion for optimization:
Consider memoizing the subpageIds array to avoid recalculating it on every validation check. You can use the useMemo hook for this:

const subpageIds = useMemo(() => 
  projectPage?.fields?.projectSubpages?.[defaultLocale]?.map(
    (subpage) => subpage.sys.id
  ) ?? [],
  [projectPage, defaultLocale]
);

Place this memoized value outside the debounced effect and use it within. This optimization would slightly improve performance, especially if the project has many subpages, by avoiding unnecessary recalculations.


126-147: LGTM: Clean render logic with a suggestion for accessibility improvement

The render logic is well-implemented, using appropriate components from Contentful's design system. The conditional rendering of error messages and the TextInput's onChange handler are correctly implemented.

A suggestion for improving accessibility:
Consider adding aria-live attributes to the error messages to ensure they are announced by screen readers when they appear. This would improve the component's accessibility. For example:

- <Text fontColor="red400">Invalid slug</Text>
+ <Text fontColor="red400" aria-live="polite">Invalid slug</Text>

- <Text fontColor="red400">
+ <Text fontColor="red400" aria-live="polite">
    Project subpage already exists with this slug
  </Text>

This change would ensure that users relying on assistive technologies are aware of validation errors as they occur.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7ae9480 and bee11ea.

📒 Files selected for processing (1)
  • apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (2)
apps/contentful-apps/pages/fields/project-subpage-slug-field.tsx (2)

1-10: LGTM: Well-structured imports and constant definition

The imports are well-organized and include all necessary dependencies for the component's functionality. The DEBOUNCE_TIME constant is appropriately defined at the top level, enhancing maintainability.


149-149: LGTM: Correct component export

The component is correctly exported as the default export, following common React practices.

@kodiakhq kodiakhq bot merged commit 26fb2c5 into main Oct 16, 2024
30 checks passed
@kodiakhq kodiakhq bot deleted the feature/contentful-apps-project-subpage-slug-field branch October 16, 2024 09:30
RunarVestmann added a commit that referenced this pull request Oct 16, 2024
…16412)

* Allow two subpages to have same slug

* Change component name

* Remove console.log

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
kodiakhq bot added a commit that referenced this pull request Oct 16, 2024
…me slug (#16412) (#16416)

* Allow two subpages to have same slug

* Change component name

* Remove console.log

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants